package com.tdly.buduizhong.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tdly.buduizhong.R;
import com.tdly.buduizhong.base.BaseActivity;
import com.tdly.util.SerialPortUtils;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import java.util.Arrays;


import biz.source_code.dsp.transform.Dft;




public class HomeActivity extends BaseActivity implements View.OnClickListener {
    private Context context = this;
    private RelativeLayout rl_title, rl_show_type, rl_fragment, rl_show_content;
    private TextView tv_title, tv_setting, tv_load, tv_save;
    private TextView tv_acc_p,tv_v_rms,tv_s_pp,tv_save_log;
    private Button bt_stop, bt_start, bt_show_arg, bt_show_freq, bt_show_time;
    private static String index = "canshuxianshi";
    private boolean flag=false;//参数
    private boolean flag2=false;//折线
    private boolean flag3=false;//

    public String str=new String();
    public String str2=null;
    public String str3=null;




    private float cypl=4000;//采样频率
    private int cycd=2048;//采样长度
    private int btl=19200;//波特率




    XYMultipleSeriesDataset mDataset;
    // 多个系列的数据集合,即多条线的数据集合
    XYSeries series;
    // 一个系列的数据，即一条线的数据集合

    XYMultipleSeriesRenderer mRenderer;
    // 多个系列的环境渲染，即整个画折线的区域
    XYSeriesRenderer r;
    // 一个系列的环境渲染，即一条线的环境渲染
    GraphicalView view;
    // 整个view


    CSThread canshu  = new CSThread();
    PPThread line =new PPThread();

    SerialPortUtils serialPortUtils =new SerialPortUtils();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        initView();
        getSetting();
        initSerialPort();

    }



    private void initSerialPort() {
        serialPortUtils.setOnDataReceiveListener(new SerialPortUtils.OnDataReceiveListener() {
            @Override
            public void onDataReceive(byte[] buffer, int size) {
//                            Log.e("参数显示", "进入数据监听事件中。。。" + new String(buffer));
                Log.e("串口连接", "run: 接收到了数据：" +Arrays.toString(buffer));//changeTool.ByteArrToHex(buffer)
                Log.e("串口连接", "run: 接收到了数据大小：" + String.valueOf(size));

                String[] data=byteToString(Arrays.toString(buffer));
                Log.e("连接", "onChanged:datalength:"+data.length+"!!!data[2]:"+data[2]);
                Message msg =mHandler.obtainMessage();
                if(!flag3&&"85".equals(data[2].trim())){//传感器准备就绪
                    msg.what=85;
                    mHandler.sendMessage(msg);
                    str=null;
                }
                if(!flag3&&"17".equals(data[2].trim())){//加速度
                    msg.what=17;
                    msg.obj=data[5]+'.'+data[6];
                    mHandler.sendMessage(msg);
                   // tv_acc_p.setText(data[5]+'.'+data[6]);
                    str=null;
                }
                if(!flag3&&"33".equals(data[2].trim())){//速度
                    msg.what=33;
                    msg.obj=data[5]+'.'+data[6];
                    mHandler.sendMessage(msg);
                    str=null;
                }
                if(!flag3&&"49".equals(data[2].trim())){//位移
                    msg.what=49;
                    int gao=Integer.valueOf(data[5].trim()).intValue();
                    int di=Integer.valueOf(data[5].trim()).intValue();
                    msg.obj=(gao*256+di)+"";
                    mHandler.sendMessage(msg);
                    str=null;
                }
                if(index.equals("pinyuboxing")||index.equals("shiyuboxing")){
                    if(!flag3&&"20".equals(data[2].trim())){//加速度波形
                        str=data[12]+","+data[13]+","+data[14]+","+data[15]+","+data[16]+","+data[17]+","+data[18]+","+data[19];
                        Log.e("第一波：",data[9]+","+data[10]+","+data[11]+","+str);
                        flag3=true;
                    }else if(flag3){
                        String tmp=Arrays.toString(buffer).replace("[", "").replace("]", "").trim();
                        if(byteToString( Arrays.toString(buffer)).length<10&&str2==null)
                        {
                            str2=tmp;
                        }
                        if(str2==null||!tmp.equals(str2)) {
                            str = str + "," + tmp;
                        }
                    }
                }


            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            tv_acc_p=findViewById(R.id.tv_acc_p);
            tv_v_rms=findViewById(R.id.tv_v_rms);
            tv_s_pp=findViewById(R.id.tv_s_pp);
            switch(msg.what){
                case 85:
                    tv_title.setText("设备连接成功");
                    break;
                case 17:
                    tv_acc_p.setText(msg.obj.toString());
                    break;
                case 33:
                    tv_v_rms.setText(msg.obj.toString());
                    break;
                case 49:
                    tv_s_pp.setText(msg.obj.toString());
                    break;
            }
        };
    };


    private void getSetting() {
        try {
            String path = Environment.getExternalStorageDirectory().getCanonicalPath() + "/setting/Setting.txt";
            String[] data = readToString(path).split(",");
            if (data != null && data.length > 2) {
                if(data[0]!=null){
                    cypl=StrToInt(data[0]);
                }
                if(data[1]!=null) {
                    cycd=StrToInt(data[1]);
                }
                if(data[2]!=null) {
                    btl=StrToInt(data[2]);
                }
            }else{
                Toast.makeText(context,"请先设置参数",Toast.LENGTH_LONG).show();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    private void initView() {
        tv_title = findViewById(R.id.tv_title);
        tv_setting = findViewById(R.id.tv_setting);
        tv_load = findViewById(R.id.tv_load);
        tv_save = findViewById(R.id.tv_save);
        rl_title = findViewById(R.id.rl_title);
        rl_show_type = findViewById(R.id.rl_show_type);
        rl_fragment = findViewById(R.id.rl_fragment);
        bt_stop = findViewById(R.id.bt_stop);
        bt_start = findViewById(R.id.bt_start);
        bt_show_arg = findViewById(R.id.bt_show_arg);
        bt_show_freq = findViewById(R.id.bt_show_freq);
        bt_show_time = findViewById(R.id.bt_show_time);
        rl_show_content = findViewById(R.id.rl_show_content);
        tv_setting.setOnClickListener(this);
        tv_load.setOnClickListener(this);
        tv_save.setOnClickListener(this);
        bt_stop.setOnClickListener(this);
        bt_start.setOnClickListener(this);
        bt_show_arg.setOnClickListener(this);
        bt_show_freq.setOnClickListener(this);
        bt_show_time.setOnClickListener(this);
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View view = layoutInflater.inflate(R.layout.include_arg,null);
        rl_fragment.addView(view);
        tv_acc_p=findViewById(R.id.tv_acc_p);
        tv_v_rms=findViewById(R.id.tv_v_rms);
        tv_s_pp=findViewById(R.id.tv_s_pp);



    }


    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.tv_setting:
                intent=new Intent(HomeActivity.this,SettingActivity.class);
                startActivityForResult(intent,20);//requestCode自己设置
                break;
            case R.id.tv_load:
                 intent=new Intent(HomeActivity.this,HistoryActivity.class);
                 startActivityForResult(intent,10);//requestCode自己设置
                 break;
            case R.id.tv_save:
                if(str3==null||str3.length()<2){
                    Toast.makeText(context,"当前没有数据，保存失败",Toast.LENGTH_SHORT).show();
                    break;
                }
                intent = new Intent(context, SaveActivity.class);
                canshu.pauseThread();
                line.pauseThread();
                intent.putExtra("str",str3);
                startActivity(intent);
                break;
            case R.id.bt_show_arg:
                index = "canshuxianshi";
                rl_show_content.setBackgroundResource(R.drawable.canshuxianshi);
                tv_load.setVisibility(View.GONE);
                tv_save.setVisibility(View.GONE);
                line.pauseThread();
                canshu.resumeThread();
                rl_fragment.removeAllViews();
                LayoutInflater layoutInflater = LayoutInflater.from(context);
                View view = layoutInflater.inflate(R.layout.include_arg,null);
                rl_fragment.addView(view);
                tv_acc_p=findViewById(R.id.tv_acc_p);
                tv_v_rms=findViewById(R.id.tv_v_rms);
                tv_s_pp=findViewById(R.id.tv_s_pp);
                break;
            case R.id.bt_show_freq:
                index = "pinyuboxing";
                canshu.pauseThread();
                line.resumeThread();
                rl_show_content.setBackgroundResource(R.drawable.pinyuboxing);
                tv_load.setVisibility(View.VISIBLE);
                tv_save.setVisibility(View.VISIBLE);
                rl_fragment.removeAllViews();
                lineView();
                break;
            case R.id.bt_show_time:
                index = "shiyuboxing";
                canshu.pauseThread();
                line.resumeThread();
                rl_show_content.setBackgroundResource(R.drawable.shiyuboxing);
                tv_load.setVisibility(View.VISIBLE);
                tv_save.setVisibility(View.VISIBLE);
                rl_fragment.removeAllViews();
                lineView();
                break;
            case R.id.bt_start:
                if(!serialPortUtils.serialPortStatus){
                    serialPortUtils.openSerialPort();
                    if(serialPortUtils.serialPortStatus){
                        tv_title.setText("连接成功");
                        Toast.makeText(context,"连接成功",Toast.LENGTH_SHORT).show();
                        Log.e("串口连接", "连接成功");
                    }
                }

                if(index.equals("canshuxianshi")) {
                    if (!flag) {
                        Thread csthread = new Thread(canshu);
                        csthread.start();
                        flag = true;
                    } else {
                        canshu.resumeThread();
                    }
                }else{
                    if(!flag2) {
                            Thread Lthread = new Thread(line);
                            Lthread.start();
                            flag2=true;
                        }else{
                            line.resumeThread();
                        }
                }

                break;
            case R.id.bt_stop:
                tv_title.setText("未连接");
                canshu.pauseThread();
                line.pauseThread();
                serialPortUtils.closeSerialPort();


        }
    }

    public void lineView() {
        // 同样是需要数据dataset和视图渲染器renderer
        mDataset = new XYMultipleSeriesDataset();
        series = new XYSeries("游标1");
        mDataset.addSeries(series);

        mRenderer = new XYMultipleSeriesRenderer();

        mRenderer.setOrientation(XYMultipleSeriesRenderer.Orientation.HORIZONTAL);
        // 设置图表的X轴的当前方向
        mRenderer.setXTitle("X轴");// 设置为X轴的标题
        mRenderer.setYTitle("Y轴");// 设置y轴的标题
        mRenderer.setAxisTitleTextSize(20);// 设置轴标题文本大小
        //mRenderer.setChartTitle("未检测到不对中故障");// 设置图表标题
        mRenderer.setChartTitleTextSize(30);// 设置图表标题文字的大小
        mRenderer.setLabelsTextSize(18);// 设置标签的文字大小
        mRenderer.setLegendTextSize(20);// 设置图例文本大小
        mRenderer.setPointSize(1f);// 设置点的大小
//        mRenderer.setYAxisMin(0);// 设置y轴最小值是0
//        mRenderer.setYAxisMax(10000);
        mRenderer.setYLabels(6);// 设置Y轴刻度个数（貌似不太准确）
        mRenderer.setXAxisMax(8);//设置X轴坐标个数


        mRenderer.setXLabels(0);// 设置只显示如1月，2月等替换后的东西，不显示1,2,3等
        mRenderer.setMargins(new int[]{20, 30, 15, 20});// 设置视图位置
        mRenderer.setPanEnabled(false, false);
        // 第一个参数设置X轴是否可滑动，第二个参数设置Y轴是够可滑动
        r = new XYSeriesRenderer();
        r.setColor(Color.GREEN);// 设置颜色
        r.setPointStyle(PointStyle.CIRCLE);// 设置点的样式
        r.setFillPoints(false);// 填充点（显示的点是空心还是实心）
        r.setDisplayChartValues(false);// 将点的值显示出来
        r.setChartValuesSpacing(10);// 显示的点的值与图的距离
        r.setChartValuesTextSize(20);// 点的值的文字大小

        // r.setFillBelowLine(true);//是否填充折线图的下方
        // r.setFillBelowLineColor(Color.GREEN);//填充的颜色，如果不设置就默认与线的
        //颜色一致
        r.setLineWidth(2);// 设置线宽



        mRenderer.addSeriesRenderer(r);
        view = ChartFactory.getLineChartView(this, mDataset, mRenderer);
        view.setBackgroundColor(Color.BLACK);
        rl_fragment.addView(view);

        //将画好折线的view添加到xml中的一个布局里
    }


    public synchronized void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }


        public class CSThread extends Thread {
        private final Object lock = new Object();
        private boolean pause = false;

        /**
         * 调用这个方法实现暂停线程
         */
        void pauseThread() {
            pause = true;
        }

        /**
         * 调用这个方法实现恢复线程的运行
         */
        void resumeThread() {
            pause = false;
            synchronized (lock) {
                lock.notifyAll();
            }
        }

        /**
         * 注意：这个方法只能在run方法里调用，不然会阻塞主线程，导致页面无响应
         */
        void onPause() {
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void run() {
            super.run();
            try {
                int index = 0;
                while (true) {
                    // 让线程处于暂停等待状态
                    while (pause) {
                        onPause();
                    }
                    try {
                        serialPortUtils.sendSerialPort(datastr[index%3]);
                        Thread.sleep(3000);
                        ++index;
                    } catch (InterruptedException e) {
                        //捕获到异常之后，执行break跳出循环
                        break;
                    }
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }

    }





    public class PPThread extends Thread {//加速度波形指令发送
        private final Object lock = new Object();
        private boolean pause = false;

        /**
         * 调用这个方法实现暂停线程
         */
        void pauseThread() {
            pause = true;
        }

        /**
         * 调用这个方法实现恢复线程的运行
         */
        void resumeThread() {
            pause = false;
            synchronized (lock) {
                lock.notifyAll();
            }
        }

        /**
         * 注意：这个方法只能在run方法里调用，不然会阻塞主线程，导致页面无响应
         */
        void onPause() {
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void run() {
            super.run();
            try {
                while (true) {
                    // 让线程处于暂停等待状态
                    while (pause) {
                        onPause();
                    }

                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    serialPortUtils.sendSerialPort(datastr[3]);
                    str3=null;
                    try {
                        Thread.sleep(4000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (str != null&&index.equals("pinyuboxing")) {
                        flag3=false;
                        str2=null;
                        str3=str;
                        String[] tmp = str.trim().split(",");
                        series.clear();
                        float max = 0, min = 0;
                        int index = 1;
                        for (int i = 0; i + 1 < tmp.length ; i += 2) {
                            float num = StrToInt(tmp[i + 1]) * 256 + StrToInt(tmp[i]);
                            if (num > max) {
                                max = num;
                            }
                            if (num < min) {
                                min = num;
                            }
                            series.add(index++, num);
                        }

                        if(Math.abs(min)<Math.abs(max)){
                            min=max*-1;
                        }else{
                            max=min*-1;
                        }

                        mRenderer.setYAxisMin(min*1.5);// 设置y轴最小值是0
                        mRenderer.setYAxisMax(max*1.5);
                        mRenderer.setXAxisMax(index);//设置X轴坐标个数
                        //动态添加数据和标题
                        view.repaint();
                        //重绘折线
                        if (series != null) {
                            str = null;
                            Log.e("index:",""+index);
                        }
                    }else if(str != null&&index.equals("shiyuboxing")) {//频谱
                        flag3=false;
                        str2=null;
                        String[] tmp = str.trim().split(",");
                        series.clear();
                        double max = 0;
                        double[] datalist=new double[tmp.length/2];
                        for (int i = 0,j=0; i + 1 < tmp.length ; i += 2) {
                            float num = StrToInt(tmp[i + 1]) * 256 + StrToInt(tmp[i]);
                            datalist[j++]=num;
                        }


                        biz.source_code.dsp.math.Complex[] complexData=Dft.goertzelSpectrum(datalist);
                        Log.e("长度：",complexData.length+"");
                        for(int i=0;i<complexData.length;i++){
                            //test1=test1+complexData[i].re()+"+"+complexData[i].im()+"i\t";
                            double y=Math.sqrt(Math.pow(complexData[i].re(),2)+Math.pow(complexData[i].im(),2));
                            double x=((double) i+1.0)/datalist.length*cypl;
                            //test2=test2+y+"\t";
                            series.add(x,y);
                            //Log.e("i:",x+" . "+y);
                            if(max<Math.abs(y)){
                                max=Math.abs(y);
                            }
                        }

                        mRenderer.setYAxisMin(0);// 设置y轴最小值是0
                        mRenderer.setYAxisMax(max*1.5);
                        mRenderer.setXAxisMax(series.getItemCount()/2);//设置X轴坐标个数
                        //动态添加数据和标题
                        view.repaint();
                        //重绘折线
                        if (series != null) {
                            str = null;
                        }
                    }
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }

    }


    public class SYThread extends Thread {//加速度波形指令发送
        private final Object lock = new Object();
        private boolean pause = false;

        /**
         * 调用这个方法实现暂停线程
         */
        void pauseThread() {
            pause = true;
        }

        /**
         * 调用这个方法实现恢复线程的运行
         */
        void resumeThread() {
            pause = false;
            synchronized (lock) {
                lock.notifyAll();
            }
        }

        /**
         * 注意：这个方法只能在run方法里调用，不然会阻塞主线程，导致页面无响应
         */
        void onPause() {
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void run() {
            super.run();
            try {
                while (true) {
                    // 让线程处于暂停等待状态
                    while (pause) {
                        onPause();
                    }

                    try {
                        if(index.equals("pinyuboxing")){
                            Thread.sleep(500);
                        }else{
                            Thread.sleep(1500);
                        }
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    serialPortUtils.sendSerialPort(datastr[3]);
                    str3=null;
                    try {
                        if(index.equals("pinyuboxing")){
                            Thread.sleep(3500);
                        }else{
                            Thread.sleep(4000);
                        }
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (str != null&&index.equals("pinyuboxing")) {
                        flag3=false;
                        str2=null;
                        str3=str;
                        String[] tmp = str.trim().split(",");
                        series.clear();
                        float max = 0, min = 0;
                        int index = 1;
                        for (int i = 0; i + 1 < tmp.length ; i += 2) {
                            float num = StrToInt(tmp[i + 1]) * 256 + StrToInt(tmp[i]);
                            if (num > max) {
                                max = num;
                            }
                            if (num < min) {
                                min = num;
                            }
                            series.add(index++, num);
                        }

                        if(Math.abs(min)<Math.abs(max)){
                            min=max*-1;
                        }else{
                            max=min*-1;
                        }

                        mRenderer.setYAxisMin(min*1.5);// 设置y轴最小值是0
                        mRenderer.setYAxisMax(max*1.5);
                        mRenderer.setXAxisMax(index);//设置X轴坐标个数
                        //动态添加数据和标题
                        view.repaint();
                        //重绘折线
                        if (series != null) {
                            str = null;
                            Log.e("index:",""+index);
                        }
                    }else if(str != null&&index.equals("shiyuboxing")) {//频谱
                        flag3=false;
                        str2=null;
                        String[] tmp = str.trim().split(",");
                        series.clear();
                        double max = 0;
                        double[] datalist=new double[tmp.length/2];
                        for (int i = 0,j=0; i + 1 < tmp.length ; i += 2) {
                            float num = StrToInt(tmp[i + 1]) * 256 + StrToInt(tmp[i]);
                            datalist[j++]=num;
                        }


                        biz.source_code.dsp.math.Complex[] complexData=Dft.goertzelSpectrum(datalist);
                        Log.e("长度：",complexData.length+"");
                        for(int i=0;i<complexData.length;i++){
                            //test1=test1+complexData[i].re()+"+"+complexData[i].im()+"i\t";
                            double y=Math.sqrt(Math.pow(complexData[i].re(),2)+Math.pow(complexData[i].im(),2));
                            double x=((double) i+1.0)/datalist.length*cypl;
                            //test2=test2+y+"\t";
                            series.add(x,y);
                            //Log.e("i:",x+" . "+y);
                            if(max<Math.abs(y)){
                                max=Math.abs(y);
                            }
                        }

                        mRenderer.setYAxisMin(0);// 设置y轴最小值是0
                        mRenderer.setYAxisMax(max*1.5);
                        mRenderer.setXAxisMax(series.getItemCount()/2);//设置X轴坐标个数
                        //动态添加数据和标题
                        view.repaint();
                        //重绘折线
                        if (series != null) {
                            str = null;
                        }
                    }
                }
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode==10&&requestCode==10){
            line.pauseThread();
            str = null;
            str2=null;
            series.clear();
            String[] tmp = data.getStringExtra("tmp").split("\t");
            String[] name=data.getStringExtra("name").trim().replace(".txt","").split("-");
            int length =tmp.length;
            if(tmp!=null&&tmp.length>0){

                if(index.equals("pinyuboxing")){//时域波形
                    series.clear();
                    double max = 0;
                    for (int i = 1; i<=tmp.length ; i++) {
                        double num = Double.parseDouble(tmp[i-1].trim());
                        if(max<Math.abs(num)){
                            max=Math.abs(num);
                        }
                        series.add(i, num);
                    }

                    mRenderer.setYAxisMin(max*-1.5);// 设置y轴最小值是0
                    mRenderer.setYAxisMax(max*1.5);
                    mRenderer.setXAxisMax(tmp.length);//设置X轴坐标个数
                    //动态添加数据和标题
                    view.repaint();
                    //重绘折线
                    Toast.makeText(context,"未检测到不对中故障",Toast.LENGTH_LONG).show();

                }else if(index.equals("shiyuboxing")){//频谱
                    series.clear();

                    double max = 0;
                    double[] datalist=new double[length];
                    Log.e("长度1：",""+length);
                    for (int i = 1; i<=length ; i++) {
                        double num = Double.parseDouble(tmp[i-1].trim());
                        datalist[i-1]=num;

                    }

                    biz.source_code.dsp.math.Complex[] complexData=Dft.goertzelSpectrum(datalist);
                        Log.e("长度：",complexData.length+"");
                        for(int i=0;i<complexData.length;i++){
                            //test1=test1+complexData[i].re()+"+"+complexData[i].im()+"i\t";
                            double y=Math.sqrt(Math.pow(complexData[i].re(),2)+Math.pow(complexData[i].im(),2));
                            double x=((double) i+1.0)/length*cypl;
                            //test2=test2+y+"\t";
                            series.add(x,y);
                       //Log.e("i:",x+" . "+y);
                       if(max<Math.abs(y)){
                           max=Math.abs(y);
                      }
                    }

                    mRenderer.setYAxisMin(0);// 设置y轴最小值是0
                    mRenderer.setYAxisMax(max*1.5);
                   mRenderer.setXAxisMax(series.getItemCount()/2);//设置X轴坐标个数
                  //动态添加数据和标题
                   view.repaint();
                    //重绘折线
                    if(name.length>1){
                        if(name[0].trim().equals("1")){
                            Toast.makeText(context,"无不对中故障-正常",Toast.LENGTH_LONG).show();
                        }else if(name[0].trim().equals("3")){
                            Log.e("name!!!!!!!!!!!!!!!!:",name[1]);
                            if(name[1].trim().equals("01")){
                                Toast.makeText(context,"不对中故障—严重故障",Toast.LENGTH_LONG).show();
                            }else if(name[1].trim().equals("02")){
                                Toast.makeText(context,"不对中故障—中期故障",Toast.LENGTH_LONG).show();
                            }else{
                                Toast.makeText(context,"不对中故障—轻微故障",Toast.LENGTH_LONG).show();
                            }
                        }
                    }else{
                        Toast.makeText(context,"未检测到不对中故障",Toast.LENGTH_LONG).show();
                    }
                }

            }else{
                Toast.makeText(context,"无数据",Toast.LENGTH_SHORT).show();
            }
        }

        if(resultCode==20&&requestCode==20){
            getSetting();
            Log.e("回调：","成功");
        }

    }


    public String readToString(String fileName) {
        String encoding = "UTF-8";
        File file = new File(fileName);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            return new String(filecontent, encoding);
        } catch (UnsupportedEncodingException e) {
            System.err.println("The OS does not support " + encoding);
            e.printStackTrace();
            return null;
        }
    }



}
